package com.course.server.util;

/**
 * ClassName: JsonUtils
 * Description:
 * date: 2021/9/12 10:28
 *
 * @author 17878
 * @since JDK 1.8
 */
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * json转换工具类
 * @author Created by MrXi on 2020/8/22
 */
@Slf4j
public class JsonUtils {

    public static ObjectMapper objectMapper=new ObjectMapper();

    static {
        //config转换的时候可以忽略掉为空的字段
//        objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
//        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
//        objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
//        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
//        objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    }

    /**
     * 把对象转换为字符串
     * @param src 对象
     * @param <T> 对象类型
     * @return 转化后的字符串
     */
    public static <T> String objToString(T src){
        if(src==null){
            return null;
        }
        try {
            return src instanceof String ? (String)src : objectMapper.writeValueAsString(src);
        } catch (Exception e) {
            log.warn("parse object to String exception,error",e);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T stringToObject(String src, TypeReference<T> typeReference){
        if(src==null || typeReference==null){
            return null;
        }
        try {
            return (T)(typeReference.getType().equals(String.class) ? src : objectMapper.readValue(src,typeReference));
        } catch (Exception e) {
            log.warn("parse String to Object exception,String:{},TypeReference<T>:{},error:{}",src,typeReference.getType(),e);
            return null;
        }
    }
}